/**
 * @file 工单操作-厂商新机配件
 * @author wangxiaokun
 * @date 2020-09-22 16:20:25
 */
layui.define(['layer', 'form', 'table', 'select2', '$http'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;
    var layer = layui.layer;
    var table = layui.table;
    var select2;

    // 根据关键字获取厂商配件
    var GET_FACTORY_PARTS_URL = '/serv/factory/getParts.action';

    var newMachineGetters = {
        getNewMachineList: () => table.cache['newMachineTable']
    };
    var newPartGetters = {
        getNewPartList: () => table.cache['newPartTable']
    };
    // 新机物流
    function renderNewMachineList(data) {
        let newMachineTable = table.render({
            elem: '#newMachineTable',
            toolbar: '#btn-add',
            defaultToolbar: [],
            cols: [
                [
                    {field: 'expressCode', title: '物流单号', width:'20%', align: 'center' , edit:'text'},
                    {field: 'expressCompanyCode', title: '物流公司', align: "center", templet: '#expressCompanySelect'},
                    {field: 'remark', title: '备注', align: 'center', edit:'text'},
                    {field: 'statusName', title: '快递状态', width:'10%', align: 'center' },
                    {fixed: 'right', title: '操作', width:'10%', align:'center', toolbar: '#delNewMachineMenu'}
                ]
            ],
            data: data
            , done: function () {
                //数据渲染完的回调。
                //由于layui 设置了超出隐藏，所以这里改变下，以兼容操作按钮的下拉菜单
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');

                // 根据已有的值回填下拉框
                layui.each($("select[tag='expressCompanyList']"), function (index, item) {
                    var elem = $(item);
                    elem.val(elem.data('value'));
                });
                form.render('select');
            },
            even: true
        });

        table.on('toolbar(newMachineTable)', function (obj) {
            if (obj.event === 'add') {

                let newMachineTable = table.cache['newMachineTable'];
                // table.cache['newMachineTable'] 无法获取input、select的值，需要手动获取

                newMachineTable.push({
                    expressCode:'',
                    expressCompanyCode:'',
                    remark:''
                });

                table.reload('newMachineTable', {
                    data: newMachineTable
                });

            }
        });

        // 删除
        table.on('tool(newMachineTable)', function(obj){
            var data = obj.data;//获得当前行数据
            var layEvent = obj.event;
            if(layEvent === 'del'){
                layer.confirm("请确认是否删除当前信息？", { title: "提醒" }, function (index) {
                    layer.close(index);
                    obj.del();
                    // 清空数组
                    let newMachine = table.cache.newMachineTable;
                    newMachine = newMachine.filter(function (item) {
                        return item.length != 0;
                    });
                    table.cache.newMachineTable = newMachine;
                });
            }
        });
    }

    // 这是监听下拉框改变
    form.on('select(expressCompanyList)', function (data) {
        var selectElem = $(data.elem);
        var tdElem = selectElem.closest("td");
        var trElem = tdElem.closest("tr");

        var item = newMachineGetters.getNewMachineList()[trElem.data("index")];
        item.expressCompanyCode = data.value;
        item.expressCompany = selectElem.find("option:selected").text();
    });

    // 这是监听下拉框改变
    form.on('select(expressCompanyList2)', function (data) {
        var selectElem = $(data.elem);
        var tdElem = selectElem.closest("td");
        var trElem = tdElem.closest("tr");

        var item = newPartGetters.getNewPartList()[trElem.data("index")];
        item.expressCompanyCode = data.value;
        item.expressCompany = selectElem.find("option:selected").text();
    });

    // 这是监听下拉框改变
    form.on('select(postAddressList)', function (data) {
        var selectElem = $(data.elem);
        var tdElem = selectElem.closest("td");
        var trElem = tdElem.closest("tr");

        var item = newPartGetters.getNewPartList()[trElem.data("index")];
        item.postAddressType = data.value;
        item.value = selectElem.find("option:selected").text();
    });

    // 厂商配件-新件
    function renderNewPartList(data) {
        var newPartTable = table.render({
            elem: '#newPartTable',
            toolbar: '#btn-add',
            defaultToolbar: [],
            cols: [
                [
                    {field: 'partFullName', title: '厂商配件/单位', width:'15%', templet: '#factoryParts', align: 'center'},
                    {field: 'number', title: '数量', align: 'center' , width:'5%', edit: 'text'},
                    {field: 'applyTypeName', title: '申请方式', width:'6%', align: 'center' },
                    {field: 'expressCode', title: '物流单号', width:'17%', align: 'center', edit:'text' },
                    {field: 'expressCompanyCode', title: '物流公司', align: "center", templet: '#expressCompanySelect2'},
                    {field: 'postAddressType', title: '邮寄对象', width:'13%', templet: '#postAddressSelect', align: 'center' },
                    {field: 'statusName', title: '物流状态', width:'7%', align: 'center' },
                    {fixed: 'right', title: '操作', align:'center', width:'7%', toolbar: '#delNewPartMenu'}
                ]
            ],
            data: data
            , done: function (res, curr, count) {

                var tableView = this.elem.next(); // 当前表格渲染之后的视图
                // for(var i in res.data){ //遍历整个表格数据 // 遍历数组不建议用in
                layui.each(res.data, function(i, item){
                    if(item.number != null){
                        tableView.find('tr[data-index=' + i + ']').find('[data-field=number]').data('edit',false)
                    }
                });

                //数据渲染完的回调。
                //由于layui 设置了超出隐藏，所以这里改变下，以兼容操作按钮的下拉菜单
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');

                // 物流公司根据已有的值回填下拉框
                layui.each($("select[tag='expressCompanyList2']"), function (index, item) {
                    var elem = $(item);
                    elem.val(elem.data('value'));
                });

                // 邮寄对象根据已有的值回填下拉框
                layui.each($("select[tag='postAddressList']"), function (index, item) {
                    var elem = $(item);
                    elem.val(elem.data('value'));
                });

                form.render('select');
            }
        });

        table.on('toolbar(newPartTable)', function (obj) {
            if (obj.event === 'add') {
                //let newPartTable = table.cache['newPartTable'];
                // table.cache['newMachineTable'] 无法获取input、select的值，需要手动获取

                var newData = {
                    applyTypeName:'后台添加'
                };

                /*table.reload('newPartTable', {
                    data: newPartTable
                });*/
                newPartGetters.getNewPartList().push(newData);
                newPartTable.reload({
                    data: newPartGetters.getNewPartList()
                })
                //form.render();
                initpartSelectBySelect2();
            }

        });

        // 删除
        table.on('tool(newPartTable)', function(obj){
            var data = obj.data;//获得当前行数据
            var layEvent = obj.event;
            if(layEvent === 'del'){
                layer.confirm("该厂商配件有对应旧件邮寄信息，删除后会同步删除对应旧件邮寄信息", { title: "提醒" }, function (index) {
                    layer.close(index);
                    obj.del();
                    // 清空数组
                    let newPart = table.cache.newPartTable;
                    newPart = newPart.filter(function(item) {
                        return item.length != 0;
                    });
                    table.cache.newPartTable = newPart;
                });
            }
            initpartSelectBySelect2();
        });

        initpartSelectBySelect2();
    }

    // 厂商配件-旧件
    function renderUsedPartList(data) {
        return table.render({
            elem: '#usedPart',
            cols: [
                [
                    {field: 'partFullName', title: '厂商配件/单位', width:'16%', align: 'center', templet: function(d){
                            return d.partFullName + '/' + d.unit;
                        } },
                    {field: 'number', title: '数量', width:'4%', align: 'center' },
                    {field: 'applyTypeName', title: '申请方式', width:'10%', align: 'center' },
                    {field: 'expressCode', title: '物流单号', width:'15%', align: 'center' },
                    {field: 'expressCompany', title: '物流公司', width:'10%', align: 'center' },
                    {field: 'address', title: '收件信息', align: 'center', templet: function(d) {
                            return d.address + '-' + d.consigneePhone;
                        }
                    }
                ]
            ],
            data: data
        });
    }

    /**
     * 配件远程搜索框
     */
    function initpartSelectBySelect2 () {

        $('.factoryPart').each(function (index) {

            select2.initRemote({
                el: this,
                url: GET_FACTORY_PARTS_URL,
                getParams: function (params) {
                    let factoryId = $('#factory-id').val();
                    return {
                        keyWord: params.term,
                        factoryId: factoryId
                    };
                },
                processor: function (data) {

                    return data.map((item) => {
                        item.id = item.value;
                        return item;
                    });
                },
                formatRepo: formatRepo
            });

            $(this).on('select2:select', function (e) {

                var selectElem = $(this);
                var tdElem = selectElem.closest("td");
                var trElem = tdElem.closest("tr");

                var item = newPartGetters.getNewPartList()[trElem.data("index")];
                item.partId = e.params.data.id;
                item.partFullName = e.params.data.text;
            });

            let partId = $(this).data('option-value');
            let partFullName = $(this).data('option-name');
            if (partId && partFullName) {
                $(this).html( $(this).html() + '<option value="'+ partId +'">'+ partFullName +'</option>');
                $(this).val(partId).trigger('change');
            }
        });


    }

    /**
     * 格式化城市列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepo (repo) {
        if (repo.loading) {
            return '查询中...'
        }

        var name = repo.text;
        var markup = '<div><div><i class="zmn-icon"></i><span>' + name + '</span></div></div>';

        return markup;
    }

    /**
     * 初始化页面
     */
    function initPage() {

        // 初始化页面所有的日期选择器
        layui.use('select2', function (select2Module) {
            select2 = select2Module;
        });

        renderNewMachineList(newMachineList);

        renderNewPartList(newPartList);

        renderUsedPartList(usedPartList);

    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        renderNewMachineList(newMachineList);

        renderNewPartList(newPartList);

        renderUsedPartList(usedPartList);

        // 保存
        form.on('submit()', function (data) {
            var addMachineList = [];
            var PartList = [];
            var verify = 0;
            newMachineGetters.getNewMachineList().forEach(item => {
                //物流单号和物流公司不能为空
                if (item.expressCompanyCode == '' || item.expressCode.trim() == '') {
                    verify = 1;
                    return;
                }
                //物流单号长度不能超过50字符
                if (item.expressCode.trim().length > 50){
                    verify = 2;
                    return;
                }
                addMachineList.push({
                    expressId: item.expressId,
                    expressCode: item.expressCode.trim(),
                    expressCompanyCode: item.expressCompanyCode,
                    expressCompany: item.expressCompany,
                    itemType: 1,
                    remark: item.remark || null
                })
            });
            if (verify == 1) {
                layer.msg("物流单号、物流公司为必填项，请检查填写");
                return false;
            }
            if (verify == 2){
                layer.msg("物流单号不能超过50位");
                return false;
            }
            if (newPartGetters != null && newPartGetters.getNewPartList() != null){
                newPartGetters.getNewPartList().forEach(item => {
                    if (item.expressCompanyCode == '' || item.expressCode.trim() == '' || item.partId == null
                        || item.partFullName == null || item.postAddressType == null || item.number == '') {
                        verify = 1;
                        return;
                    }
                    if (item.expressCode.trim().length > 50){
                        verify = 2;
                        return;
                    }
                    PartList.push({
                        fcOrderPartId: item.fcOrderPartId,
                        postId: item.postId,
                        factoryId: $("#factory-id").val(),
                        applyType: 1,
                        partId: item.partId,
                        partFullName: item.partFullName,
                        number: item.number,
                        postTarget: item.postAddressType,
                        expressCode: item.expressCode.trim(),
                        expressCompanyCode: item.expressCompanyCode,
                        expressCompany: item.expressCompany,
                        remark: item.remark || null
                    });
                });
                if (verify == 1) {
                    layer.msg("厂商配件、数量、物流单号、物流公司、邮寄对象为必填项，请检查填写");
                    return false;
                }
                if (verify == 2){
                    layer.msg("物流单号不能超过50位");
                    return false;
                }
                data.field.partDIOS = PartList;
            }

            data.field.orderPostList = addMachineList;
            data.field.newPartVOS = newPartList;
            data.field.oldOrderPostList = newMachineList;
            $http.lockSave('/work/modify/save/newMachinePart.action', data.field, data.elem).then(function () {
                layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                    opCommonUtils.goOperateHome();
                });
            }, function (msg) {
                layer.msg(msg);
            });
            return false;
        });

    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }

    // 初始化
    init();
    exports('oms_work_modify_newmachinepart');
});
